package cn.com.homeyoda.aimate.aihealth.ui.record;

import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.FACE_ID;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.util.Pair;
import androidx.databinding.library.baseAdapters.BR;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.github.AAChartModel.AAChartCore.AAChartCreator.AAChartModel;
import com.github.AAChartModel.AAChartCore.AAChartCreator.AAChartView;
import com.github.AAChartModel.AAChartCore.AAChartCreator.AASeriesElement;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartLineDashStyleType;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartType;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAChart;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AALabels;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAMarker;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAOptions;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPlotLinesElement;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAStyle;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AATitle;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAXAxis;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAYAxis;
import com.github.AAChartModel.AAChartCore.AATools.AAGradientColor;
import com.github.AAChartModel.AAChartCore.AATools.AALinearGradientDirection;
import com.google.android.material.datepicker.MaterialDatePicker;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseFragment;
import cn.com.homeyoda.aimate.aihealth.bean.VisualBean;
import cn.com.homeyoda.aimate.aihealth.databinding.FragmentHeartRateRecordBinding;
import cn.com.homeyoda.aimate.aihealth.ui.my.family.FamilyViewModel;
import cn.com.homeyoda.aimate.aihealth.utils.DateFormatUtil;

/**
 * 心率记录
 */
public class HeartRateRecordFragment extends BaseFragment<FragmentHeartRateRecordBinding, FamilyViewModel> {

    private String faceId;
    private int currentIndex = 10;
    private VisualRecordAdapter visualRecordAdapter;
    Date currentDate = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat dateDayFormat = new SimpleDateFormat("yyyy-MM-dd");
    private String startTime = "2025-04-10 00:00:00";
    private String endTime = dateFormat.format(currentDate);

    public static HeartRateRecordFragment newInstance(String faceId) {
        HeartRateRecordFragment fragment = new HeartRateRecordFragment();
        Bundle args = new Bundle();
        args.putString(FACE_ID, faceId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public FamilyViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(FamilyViewModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        if (getArguments() != null) {
            faceId = getArguments().getString(FACE_ID);
            updateFaceId(faceId);
        }
        initView();
    }

    public void updateFaceId(String faceId) {
        if (TextUtils.isEmpty(faceId)) return;
        this.faceId = faceId;

        viewModel.getVisualRecord(faceId, "1", startTime, endTime, 10);
//        viewModel.getVisualRecord(faceId, "1", "", "", 10);
    }

    private void initView() {
        binding.btnTen.setChecked(true);
        binding.cardDatePicker.setOnClickListener(v -> showTimedialog());
        binding.btnTen.setOnClickListener(v -> setBtnChecked(10));
        binding.btnThirty.setOnClickListener(v -> setBtnChecked(30));
        binding.btnNinety.setOnClickListener(v -> setBtnChecked(90));
        binding.tvTimePeriod.setText("2025-04-10" + "至" + dateDayFormat.format(currentDate));
        initRecyclerView();
    }

    private void showTimedialog() {
        // 定义日期选择器
        MaterialDatePicker<Pair<Long, Long>> datePicker = MaterialDatePicker.Builder.dateRangePicker()
                .setTitleText("选择日期范围")
                .setSelection(Pair.create(MaterialDatePicker.todayInUtcMilliseconds(),
                        MaterialDatePicker.todayInUtcMilliseconds()))
                .build();

        // 显示选择器
        datePicker.show(getFragmentManager(), "DATE_PICKER");

        // 处理选择结果
        datePicker.addOnPositiveButtonClickListener(selection -> {
            Long startDate = selection.first;
            Long endDate = selection.second;

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            String dateRange = sdf.format(new Date(startDate)) + "至" +
                    sdf.format(new Date(endDate));
            startTime = sdf.format(new Date(startDate)) + " 00:00:00";
            endTime = sdf.format(new Date(endDate)) + " 23:59:59";
            binding.tvTimePeriod.setText(dateRange);
            setBtnChecked(currentIndex);
            Log.i("huage", "textString====" + dateRange);
        });
    }

    private void setBtnChecked(int days) {
        binding.btnTen.setChecked(days == 10);
        binding.btnThirty.setChecked(days == 30);
        binding.btnNinety.setChecked(days == 90);
//        if (currentIndex == days) return;
        currentIndex = days;
//        binding.tvTimePeriod.setText(DateFormatUtil.getFormattedTimeRange(days));
//        viewModel.getVisualRecord(faceId, "1", "", "", days);
        viewModel.getVisualRecord(faceId, "1", startTime, endTime, days);
    }

    private void initRecyclerView() {
        visualRecordAdapter = new VisualRecordAdapter(R.layout.heart_rate_record_item);
        binding.setLayoutManager(new LinearLayoutManager(getActivity()));
        DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.divider_transparent_2));
        binding.rvPhysicalExam.addItemDecoration(divider);
        View headerView = LayoutInflater.from(getContext()).inflate(R.layout.heart_rate_record_header, null);
        View footerView = LayoutInflater.from(getContext()).inflate(R.layout.heart_rate_record_footer, null);
        visualRecordAdapter.addHeaderView(headerView);
        visualRecordAdapter.addFooterView(footerView);
        binding.setAdapter(visualRecordAdapter);
    }

    private void aaChartView(List<VisualBean.DataBean> visualDataList) {

        int maxValue = 0;
        int minValue = 0;
        List<String> dateList = new ArrayList<>();
        List<Integer> valueList = new ArrayList<>();
        for (VisualBean.DataBean visualData : visualDataList) {
            if (maxValue == 0 || minValue == 0) {
                maxValue = visualData.getValueMax();
                minValue = visualData.getValueMin();
            }
            dateList.add(DateFormatUtil.formatToMMDD(visualData.getAddTime()));
            valueList.add(visualData.getValue());
        }

        binding.aaChartContainer.removeAllViews();
        AAChartView aaChartView = new AAChartView(getContext());
        binding.aaChartContainer.addView(aaChartView);
        aaChartView.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.divider_transparent));
        aaChartView.setIsClearBackgroundColor(true);

        Object[][] blueStopsArr = new Object[][]{
                {0.0, "#00BFFF00"},
                {0.5, "#00BFFF00"},
                {1.0, "#00BFFF1A"},
        };

        Map<String, Object> gradientBlueColorDic = AAGradientColor.linearGradient(
                AALinearGradientDirection.ToTop,
                blueStopsArr
        );

        // 配置 AAChartModel
        AAChartModel aaChartModel = new AAChartModel()
                .chartType(AAChartType.Areaspline)
                .title("")
                .dataLabelsEnabled(false)
                .markerRadius(0)
                .yAxisTitle("")
                .legendEnabled(false)
                .yAxisGridLineWidth(0f)
                .tooltipEnabled(false)
                .dataLabelsStyle(new AAStyle().color("#000000CC").fontSize(20f))
                .series(new AASeriesElement[]{
                        new AASeriesElement()
                                .name("")
                                .color("#00BFFF")
                                .lineWidth(2f)
                                .fillColor(gradientBlueColorDic)
                                .fillOpacity(0.5f)
                                .data(valueList.toArray(new Integer[0]))
                                .enableMouseTracking(false) // 禁用鼠标跟踪
                                .showInLegend(false)        // 不在 legend 中显示
                                .marker(new AAMarker().enabled(false)) // 不显示 marker 点
                });

        // 设置辅助线
        AAOptions aaOptions = aaChartModel.aa_toAAOptions();
        aaOptions.chart(new AAChart().type(aaChartModel.chartType).marginTop(20));
        aaOptions.xAxis(new AAXAxis()
                        .tickInterval(3)
                        .categories(dateList.toArray(new String[0]))
                        .labels(new AALabels()
                                .style(new AAStyle()
                                        .color("#000000CC")
                                        .fontSize(20f)
                                )
                                .x(20f)
                                .y(40f)
                        )
                )
                .yAxis(new AAYAxis()
                        .min(40)
                        .max(120)
                        .labels(new AALabels()
                                .style(new AAStyle()
                                        .color("#00000066")
                                        .fontSize(18f)
                                        .textAlign("right")
                                )
                                .x(5f)
                                .y(-2f)
                        )
                        .tickInterval(10)
                        .offset(10f)
                        .gridLineColor("#6C7B8A1A")
                        .gridLineWidth(1f)
                        .title(new AATitle().text(""))
                        .plotLines(new AAPlotLinesElement[]{
                                new AAPlotLinesElement().color("#FF3333").dashStyle(AAChartLineDashStyleType.ShortDash).value(maxValue).width(2f),
                                new AAPlotLinesElement().color("#5ECFAC").dashStyle(AAChartLineDashStyleType.ShortDash).value(minValue).width(2f),
                        }));

        // 渲染图表
        aaChartView.aa_drawChartWithChartOptions(aaOptions);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.visualData.observe(this, visualData -> {
            visualRecordAdapter.setNewData(visualData);
            aaChartView(visualData);
        });
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_heart_rate_record;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
